package com.lsy.android.pingpang;

import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.lsy.android.pingpang.bluetooth.BluetoothService;
import com.lsy.android.pingpang.tool.Tool;
import com.lsy.android.pingpang.view.BluetoothClientView;
import com.lsy.android.pingpang.view.BluetoothServerView;
import com.lsy.android.pingpang.view.BluetoothView;
import com.lsy.android.pingpang.view.BluetoothView.DataCallback;
import com.lsy.android.pingpang.view.GameView;
import com.umeng.analytics.MobclickAgent;

public class BluetoothGameActivity extends Activity implements DataCallback {

	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_DEVICE_NAME = 4;
	public static final int MESSAGE_TOAST = 5;

	public static final String DEVICE_NAME = "device_name";
	public static final String TOAST = "toast";

	private static final int REQUEST_ENABLE_BT = 3;

	public static GameView sJogo;
	public static boolean sIsConnected = false;
	/** 是否是服务端 */
	public static boolean sIsServer = false;
	private BluetoothService mBluetoothService = null;
	private Thread mSendThread;
	private TextView mTitle;
	private Button mBtnStart;
	private Dialog mBluetoothDialog;

	private final Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_STATE_CHANGE:
				switch (msg.arg1) {
				case BluetoothService.STATE_CONNECTED:
					sIsConnected = true;
					break;
				case BluetoothService.STATE_CONNECTING:
					sIsConnected = false;
					break;
				case BluetoothService.STATE_LISTEN:
					sIsConnected = false;
					break;
				case BluetoothService.STATE_NONE:
					sIsConnected = false;
					break;
				}
				break;
			case MESSAGE_WRITE:

				break;
			case MESSAGE_READ:
				break;
			case MESSAGE_DEVICE_NAME:
				String deviceName = msg.getData().getString(DEVICE_NAME);
				Toast.makeText(getApplicationContext(),
						"Connected to " + deviceName, Toast.LENGTH_SHORT)
						.show();
				if (sIsServer) {
					mTitle.setText("已经连接到" + deviceName + "\n" + "可以开始游戏");
					mBtnStart.setEnabled(true);
				}
				if(mBluetoothDialog!=null){
					mBluetoothDialog.cancel();
				}
				sIsConnected = true;
				break;
			case MESSAGE_TOAST:
				Toast.makeText(getApplicationContext(),
						msg.getData().getString(TOAST), Toast.LENGTH_SHORT)
						.show();
				break;
			}
		}
	};

	@Override
	protected void onCreate(Bundle paramBundle) {
		super.onCreate(paramBundle);
		sIsServer = getIntent().getBooleanExtra("is_server", false);
		if (sIsServer) {
			sJogo = new BluetoothServerView(this);
		} else {
			sJogo = new BluetoothClientView(this);
		}
		setContentView(sJogo);
		mSendThread = new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					if (sIsConnected) {
						try {
							// TODO:发送数据
							mBluetoothService.write(Tool.ObjectToByte(sJogo
									.getDataBean()));
							Thread.sleep(5);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
		});
		mSendThread.start();
		if (sIsServer) {
			ensureDiscoverable();
			final Dialog dialog = new Dialog(this, R.style.gameover_dialog);
			dialog.setCancelable(false);
			View view = LayoutInflater.from(this).inflate(
					R.layout.gameowait_dialog, null);
			mTitle = (TextView) view.findViewById(R.id.gamewait_title);
			mBtnStart = (Button) view.findViewById(R.id.btn_game_start);
			mBtnStart.setEnabled(false);
			mBtnStart.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
			Button exit = (Button) view.findViewById(R.id.btn_game_exit);
			exit.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					BluetoothGameActivity.this.finish();
				}
			});
			dialog.setContentView(view);
			dialog.show();
		} else {
			mBluetoothDialog = new Dialog(this, R.style.setting_dialog);
			mBluetoothDialog.setCancelable(false);
			mBluetoothDialog.setContentView(new BluetoothView(this, mBluetoothDialog, this));
			mBluetoothDialog.show();
		}
	}

	@Override
	public void onStart() {
		super.onStart();
		if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
			Intent enableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_ENABLE);
			startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
		} else {
			if (mBluetoothService == null) {
				mBluetoothService = new BluetoothService(this, mHandler);
			}
		}
	}

	@Override
	public synchronized void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		if (mBluetoothService != null) {
			if (mBluetoothService.getState() == BluetoothService.STATE_NONE) {
				mBluetoothService.start();
			}
		}
	}
	
	@Override
	public void onPause() {
	    super.onPause();
	    MobclickAgent.onPause(this);
	}

	private void connectDevice(String address) {
		BluetoothDevice device = BluetoothAdapter.getDefaultAdapter()
				.getRemoteDevice(address);
		mBluetoothService.connect(device, true);
	}

	private void ensureDiscoverable() {
		if (BluetoothAdapter.getDefaultAdapter().getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
			Intent discoverableIntent = new Intent(
					BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
			discoverableIntent.putExtra(
					BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 120);
			startActivity(discoverableIntent);
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			if (resultCode == Activity.RESULT_OK) {
				mBluetoothService = new BluetoothService(this, mHandler);
			} else {
				Toast.makeText(this, "蓝牙错误！", Toast.LENGTH_SHORT).show();
				finish();
			}
		}
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showExitDialog();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onReturnData(String adress) {
		if (!TextUtils.isEmpty(adress)) {
			connectDevice(adress);
		}
	}

	@Override
	protected void onDestroy() {
		sIsConnected = false;
		mBluetoothService.stop();
		super.onDestroy();
	}

	private void showExitDialog() {
		final Dialog dialog = new Dialog(this, R.style.exit_dialog);
		View view = LayoutInflater.from(this).inflate(R.layout.exit_dialog,
				null);
		dialog.setContentView(view);
		Button ok = (Button) view.findViewById(R.id.btn_ok);
		ok.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
				BluetoothGameActivity.this.finish();
			}
		});
		Button cancel = (Button) view.findViewById(R.id.btn_cancel);
		cancel.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.cancel();
			}
		});
		dialog.show();
	}

}
